package cn.edu.ysu.zry.util;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @program: XieyiBlockChainOS
 * @description: 哈希算法 - SHA256
 * @author: Ruiyuan Zhang
 * @create: 2020-04-20 10:40
 */
public class SHA256 {

    /**
     * 配置信息
     */
    public static int HASH_LENGTH=32; // 哈希值的字节数
    /**
     * 利用java原生的摘要实现SHA256加密
     * @param data 加密后的报文
     * @return
     */
    public static byte[] getSHA256(byte[]data){
        MessageDigest messageDigest;
        byte encodeByte[]=null;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(data);
//            encodeStr =;
            encodeByte=messageDigest.digest();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return encodeByte;
    }
    /**
     * 将byte转为16进制
     * @param bytes
     * @return
     */
    private static String byte2Hex(byte[] bytes){
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i=0;i<bytes.length;i++){
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length()==1){
                //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String str="kkkkkddddd000000000000dddkkkk";//cc16e7b320633ffb61e916f7b9ea35623bd884ffd65ff1ec4c803b5b241df8e9   a02fec91e1717153e57682fa6a833e9fcdc9e27f9623012cdf580ba91167acd7
        byte data[]= str.getBytes("UTF-8");
        byte encode[]=getSHA256(data);
        System.out.println(encode.length);
        String hashStr =  byte2Hex(encode);
        System.out.println("哈希编码："+hashStr);

    }
}
